package com.rytong.tools.utils;

import com.rytong.tools.R;
import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

/**
 * AppAntiService.java 客户端防劫持
 * 
 * @author cheng.l 2013-9-22 下午01:23:37
 */
public class AppAntiService extends Service {
	public static boolean isPressHomeKey = false;
	private boolean isShow = false;
	// activity管理器
	private ActivityManager am;
	// package包管理器
	private PackageManager pm;
	// 运行的周期时间
	private int circle = 2000;
	private boolean shouldLoop = true;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		//startForeground(19901008, new Notification());
		handler.sendEmptyMessage(0);
	}
	
	/**
	 * handler
	 */
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(!AppAntiService.isPressHomeKey){
				String packageName = getTopPackageName();
				if(!isShow && null != packageName && !packageName.equalsIgnoreCase("com.bankcomm")){
					Toast.makeText(AppAntiService.this, R.string.app_warn_message1, 10000).show();
					isShow = true;
				}else if(null != packageName && packageName.equalsIgnoreCase("com.bankcomm")){
					isShow = false;
				}
			}
			if (shouldLoop) {
				//周期性检查
				handler.sendEmptyMessageDelayed(0, circle);
			}
		}
	};
	
	/**
	 * 等到当前运行栈顶的程序
	 * @return
	 */
	public String getTopPackageName(){
		// 当前栈管理器中的栈顶的运行程序
		if (null == pm) {
			pm = getPackageManager();
		}
		if (null == am) {
			am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		}
		return am.getRunningTasks(1).get(0).topActivity.getPackageName();
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		shouldLoop = false;
		super.onDestroy();
	}
}
